package com.ojoin.trade.common.web.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.web.domain.BaseEntity;
import com.ojoin.trade.common.web.domain.Office;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Role;
import com.ojoin.trade.common.web.domain.User;
import com.ojoin.trade.common.web.service.SysManageService;

@Controller
@RequestMapping(value = "sys/role")
public class RoleController extends SimpleBaseController {

	@Autowired
	private SysManageService systemService;

	@ModelAttribute("role")
	public Role get(@RequestParam(required = false) Integer id) {
		if (null != id) {
			return systemService.getRole(id);
		} else {
			return new Role();
		}
	}
	
	@RequiresPermissions("sys:role:view")
	@ResponseBody
	@RequestMapping(value ="list")
	public Result list(Role role) {
		List<Role> list = systemService.getRoleList();
		return new Result(Result.Status.OK, list);
	}

	@RequiresPermissions("sys:role:view")
	@ResponseBody
	@RequestMapping(value = "form")
	public Result form(Role role) {
		Map ret = new HashMap();
		if (role.getOffice() == null) {
			role.setOffice(systemService.getUser().getOffice());
		}
		ret.put("role", role);
		ret.put("menuList", systemService.findAllMenuAndButton());
		ret.put("officeList", systemService.getOfficeList());
		return new Result(Result.Status.OK, ret);
	}

	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public Result save(Role role) {
		String ret;
		boolean isOk=false;
		if (!systemService.getUser().isAdmin()
				&& role.getSysData().equals(Constants.YES)) {
			ret = "越权操作，只有超级管理员才能修改此数据！";
		}

		if (!"true".equals(checkName(role.getOldName(), role.getName()))) {
			ret = "保存角色'" + role.getName() + "'失败, 角色名已存在";
		}

		systemService.saveRole(role);
		isOk=true;
		
		ret = "保存角色'" + role.getName() + "'成功";
		return new Result(isOk?Result.Status.OK:Result.Status.WARNING, ret);
	}

	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public Result delete(Role role) {
		String ret;
		if (!systemService.getUser().isAdmin()
				&& role.getSysData().equals(Constants.YES)) {
			ret = "越权操作，只有超级管理员才能修改此数据！";
		}
		role.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
		systemService.deleteRole(role);
		ret = "删除角色成功";
		return new Result(Result.Status.OK, ret);
	}

	/**
	 * 角色分配页面
	 * 
	 * @param role
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "assign")
	public Result assign(Role role) {
		List<User> userList = systemService.findUser(new User(new Role(role
				.getId())));
		return new Result(Result.Status.OK, userList);

	}

	/**
	 * 角色分配 -- 打开角色分配对话框
	 * 
	 * @param role
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:role:view")
	@ResponseBody
	@RequestMapping(value = "usertorole")
	public Result selectUserToRole(Role role) {
		Map ret = new HashMap();
		List<User> userList = systemService.findUser(new User(new Role(role
				.getId())));
		ret.put("role", role);
		ret.put("userList", userList);
		ret.put("selectIds", CommonUtils.extractToString(userList, "id", ","));
		ret.put("officeList", systemService.getOfficeList());
		return new Result(Result.Status.OK, ret);
	}

	/**
	 * 角色分配 -- 根据部门编号获取用户列表
	 * 
	 * @param officeId
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sys:role:view")
	@ResponseBody
	@RequestMapping(value = "users")
	public List<Map<String, Object>> users(Integer officeId) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		User user = new User();
		user.setOffice(new Office(officeId));
		List<User> page = systemService.findUser(user);
		for (User e : page) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", 0);
			map.put("name", e.getName());
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 角色分配 -- 从角色中移除用户
	 * 
	 * @param userId
	 * @param roleId
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "outrole")
	public Result outrole(Integer userId, Integer roleId) {
		Role role = systemService.getRole(roleId);
		User user = systemService.getFromDB(userId);
		String ret;
		boolean isDoOk=false;
		if (systemService.getUser().getId().equals(userId)) {
			ret = "无法从角色【" + role.getName() + "】中移除用户【" + user.getName()
					+ "】自己！";
		} else {
			if (user.getRoleList().size() <= 1) {
				ret = "用户【" + user.getName() + "】从角色【" + role.getName()
						+ "】中移除失败！这已经是该用户的唯一角色，不能移除。";
			} else {
				Boolean flag = systemService.outUserInRole(role, user);
				if (!flag) {
					ret = "用户【" + user.getName() + "】从角色【" + role.getName()
							+ "】中移除失败！";
				} else {
					isDoOk=true;
					ret = "用户【" + user.getName() + "】从角色【" + role.getName()
							+ "】中移除成功！";
				}
			}
		}
		return new Result(isDoOk, ret);
	}

	/**
	 * 角色分配
	 * 
	 * @param role
	 * @param idsArr
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "assignrole")
	public Result assignRole(Role role, Integer[] idsArr) {
		StringBuilder msg = new StringBuilder();
		int newNum = 0;
		for (int i = 0; i < idsArr.length; i++) {
			User user = systemService.assignUserToRole(role,
					systemService.get(idsArr[i]));
			if (null != user) {
				msg.append("<br/>新增用户【" + user.getName() + "】到角色【"
						+ role.getName() + "】！");
				newNum++;
			}
		}
		return new Result(Result.Status.OK, "已成功分配 " + newNum + " 个用户" + msg);
	}

	/**
	 * 验证角色名是否有效
	 * 
	 * @param oldName
	 * @param name
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldName, String name) {
		try {
			name=URLDecoder.decode(name,Constants.ENCODING);
			oldName=URLDecoder.decode(oldName,Constants.ENCODING);
		} catch (UnsupportedEncodingException e) {}
		
		if (name != null && name.equals(oldName)) {
			return "true";
		} else if (name != null && systemService.getRoleByName(name) == null) {
			return "true";
		}
		return "false";
	}
	
	/**
	 * 验证角色英文名是否有效
	 * @param oldName
	 * @param name
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "checkEnname")
	public String checkEnname(String oldEnname, String enname) {
		if (enname!=null && enname.equals(oldEnname)) {
			return "true";
		} else if (enname!=null && systemService.getRoleByEnname(enname) == null) {
			return "true";
		}
		return "false";
	}

}
